package com.itheima.controller.store;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.itheima.controller.BaseServlet;
import com.itheima.domain.store.QuestionItem;
import com.itheima.utils.BeanUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/*
反射获取当前访问路径
 */
@WebServlet("/store/questionItem/*")
public class QuestionItemServlet extends BaseServlet {
    //查询所有(分页)
    private void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String questionId = req.getParameter("questionId");
        //调用业务层查找所有方法(要根据questionId查找)
        List<QuestionItem> list=questionItemService.findAll(questionId);
        req.setAttribute("questionId",questionId);
        req.setAttribute("page",list);
//        将pageinfo重定向到list.jsp页面
        req.getRequestDispatcher("/pages/store/questionItem/list.jsp").forward(req,resp);
    }

    //新增
    private void saveOrUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取对象并封装到questionItem中
        Map<String, String[]> map = req.getParameterMap();
        QuestionItem questionItem = BeanUtil.fillBean(req, QuestionItem.class, "yyyy-MM-dd");
        if(StringUtils.isNotBlank(req.getParameter("id"))){
            questionItemService.update(questionItem);
        }else {
            questionItemService.save(questionItem);
        }
        //新增完成后再次调用servlet查找所有方法
        findAll(req,resp);
    }
    //删除
    private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取要删除的id
        String id = req.getParameter("id");
        System.out.println(id);
        //调用业务层删除方法
        boolean flag=questionItemService.deleteById(id);
        if(flag){
            //删除成功则调用servlet查找所有方法
            findAll(req,resp);
        }else{
            //失败则跳转到错误页面
            req.getRequestDispatcher("/pages/error.jsp").forward(req,resp);
        }
    }
    //编辑第一次点击实际是根据id获取对象,并把id传给编辑框的对象
    private void toUpdate(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //获取当前id
        String id = req.getParameter("id");
        QuestionItem questionItem=questionItemService.findById(id);
        req.setAttribute("questionItem",questionItem);
        findAll(req,resp);
    }

}
